#include "PMFile.h"

PMFile::PMFile(void):m_Handle(INVALID_HANDLE_VALUE)
{

}

PMFile::~PMFile(void)
{
	Close();
}

DWORD PMFile::OpenWrite(LPCTSTR lpFileName,DWORD mode)
{
	m_Handle  = CreateFile(lpFileName,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,mode,NULL);
    if(m_Handle == INVALID_HANDLE_VALUE)
    {
        return FALSE;
    }
	return TRUE;
}

DWORD PMFile::OpenRead(LPCTSTR lpFileName,DWORD mode)
{
	m_Handle  = CreateFile(lpFileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,mode,NULL);
    if(m_Handle == INVALID_HANDLE_VALUE)
    {
        return FALSE;
    }
	return TRUE;
}
DWORD PMFile::Close(void)
{
    if(m_Handle != INVALID_HANDLE_VALUE)
    {
        CloseHandle(m_Handle);
		m_Handle = INVALID_HANDLE_VALUE;
    }
	return TRUE;
}

DWORD PMFile::Write(LPVOID buf,DWORD bufsize)
{
	DWORD dwwrite;
	return WriteFile(m_Handle,buf,bufsize,&dwwrite,0);
}

DWORD PMFile::Read(LPVOID buf,DWORD bufsize)
{
	DWORD dwread;
	return ReadFile(m_Handle,buf,bufsize,&dwread,0);
}

DWORD PMFile::CheckBlank(LPBYTE buf,DWORD bufsize,LPDWORD plen)
{
	BYTE *p;
	DWORD ibuffer;

	for(p=buf,ibuffer=0;ibuffer<bufsize;ibuffer++,p++)
	{

		if(*p==' ')
		{
			//return the number of charactors in a line
			*plen=ibuffer;
			return TRUE;
		}
	}
	*plen=ibuffer;
	return FALSE;
}
DWORD PMFile::ReadLine(LPVOID buf,DWORD bufsize,LPDWORD pNextReadIndex)
{
	DWORD dwread;
	BYTE linebuffer[200],*p;
	DWORD ValidLen,ioffset=0,Filelen,readleft,toread;
	DWORD CurPointer;

	CurPointer=GetCurrentPointer();

	readleft=Filelen=FileSize();
	readleft-=CurPointer;
	while(readleft>0)
	{
		//get toread
		if(readleft>sizeof(linebuffer))
			toread=sizeof(linebuffer);
		else
			toread=readleft;
		//read once
		if(ReadFile(m_Handle,linebuffer,toread,&dwread,0))
		{
			if(!CheckBlank(linebuffer,dwread,&ValidLen))
			{
				ioffset+=ValidLen;
			}
			else
			{
				ioffset+=ValidLen;
				goto end_found;
			}
			readleft-=dwread;
		}
	}
end_found:
	if(bufsize<ioffset+1)
		return FALSE;
	PMFile::SetPointer(CurPointer);
	p=(BYTE *)buf;
	ReadFile(m_Handle,buf,ioffset,&dwread,0);
	*(p+ioffset)=0;
	PMFile::SetPointer(ioffset+CurPointer+1);
	*pNextReadIndex=ioffset;
	return TRUE;
}

DWORD PMFile::GetCurrentPointer()
{
	return SetFilePointer(m_Handle,0,0,FILE_CURRENT);
}

DWORD PMFile::SetPointer(LONG offset,DWORD method)
{
	return SetFilePointer(m_Handle,offset,0,method);
}